<template>
  <div class="permission-management">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧角色列表 -->
      <div class="role-section">
        <div class="section-header">
          <h3>角色列表</h3>
        </div>
        <el-menu
          :default-active="String(currentRole?.rid)"
          class="role-menu"
          @select="handleRoleSelect"
        >
          <el-menu-item 
            v-for="role in roles" 
            :key="role.rid"
            :index="String(role.rid)"
          >
            <span>{{ role.rname }}</span>
            <el-tag size="small" class="role-tag">{{ role.permissionCount }}项权限</el-tag>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧权限配置 -->
      <div class="permission-section">
        <template v-if="currentRole">
          <div class="section-header">
            <h3>{{ currentRole.rname }} - 权限配置</h3>
            <div class="header-actions">
              <el-button-group>
                <el-button size="small" @click="handleCheckAll">全选</el-button>
                <el-button size="small" @click="handleUncheckAll">取消全选</el-button>
              </el-button-group>
              <el-button type="primary" size="small" @click="handleSavePermissions" :loading="saving">
                保存更改
              </el-button>
            </div>
          </div>

          <!-- 权限分组展示 -->
          <div v-loading="isLoading" class="permission-groups">
            <template v-if="!isLoading && permissions.length > 0">
              <el-card v-for="group in groupedPermissions" :key="group.name" class="permission-group">
                <template #header>
                  <div class="group-header">
                    <h4>{{ group.name }}</h4>
                    <el-checkbox
                      v-model="group.checked"
                      :indeterminate="group.indeterminate"
                      @change="handleGroupCheckChange($event, group)"
                    />
                  </div>
                </template>
                <div class="permission-list">
                  <el-checkbox-group v-model="selectedPermissions">
                    <el-checkbox
                      v-for="permission in group.permissions"
                      :key="permission.pid"
                      :label="permission.pid"
                      :disabled="isPermissionDisabled(permission)"
                    >
                      <div class="permission-item">
                        <span class="permission-name">{{ permission.pname }}</span>
                        <el-tooltip :content="permission.description" placement="top">
                          <span class="permission-code">{{ permission.pcode }}</span>
                        </el-tooltip>
                      </div>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-card>
            </template>
            <el-empty v-else-if="!isLoading && permissions.length === 0" description="暂无权限数据" />
          </div>
        </template>
        <div v-else class="no-role-selected">
          <el-empty description="请选择一个角色来配置权限" />
        </div>
      </div>
    </div>

    

    <!-- 新增权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="新增权限"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="权限大类" prop="group">
          <el-select
            v-model="permissionForm.group"
            placeholder="请选择权限所属大类"
            class="w-full"
          >
            <el-option
              v-for="group in permissionGroups"
              :key="group.value"
              :label="group.label"
              :value="group.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限名称" prop="pname">
          <el-input
            v-model="permissionForm.pname"
            placeholder="请输入权限名称"
          />
        </el-form-item>
        <el-form-item label="权限编码" prop="pcode">
          <el-input
            v-model="permissionForm.pcode"
            placeholder="格式：模块:操作，如 user:create"
          />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitPermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { roleApi, permissionApi } from '../api/console'

// 接口类型定义
interface Role {
  rid: number
  rname: string
  describes: string
  permissionCount?: number // 用于左侧列表显示
  permissionIds?: number[] // 从关联接口获取，用于右侧初始化选中状态
}

interface Permission {
  pid: number
  pname: string
  pcode: string
  description: string
  group?: string
}

interface PermissionGroup {
  name: string
  permissions: Permission[]
  checked: boolean
  indeterminate: boolean
}

// 状态变量
const roles = ref<Role[]>([])
const permissions = ref<Permission[]>([]) // 存储所有权限列表
const currentRole = ref<Role | null>(null)
const selectedPermissions = ref<number[]>([])
const searchQuery = ref('')
const roleDialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const permissionDialogVisible = ref(false)
const permissionForm = ref({
  group: '', // 权限大类
  pname: '', // 权限名称
  pcode: '', // 权限编码
  description: '' // 权限描述
})
const isLoading = ref(false)

// 表单相关
const roleFormRef = ref<FormInstance>()
const roleForm = ref({
  rname: '',
  describes: ''
})
const roleRules = {
  rname: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  describes: [
    { max: 150, message: '最大长度为 150 个字符', trigger: 'blur' }
  ]
}

const permissionFormRef = ref()
const permissionRules = {
  group: [
    { required: true, message: '请选择权限大类', trigger: 'change' }
  ],
  pname: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  pcode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z]+:[a-z]+$/, message: '格式为：模块:操作，如 user:create', trigger: 'blur' }
  ],
  description: [
    { max: 150, message: '最大长度为 150 个字符', trigger: 'blur' }
  ]
}

// 权限大类选项
const permissionGroups = [
  { label: '用户管理', value: 'user' },
  { label: '角色管理', value: 'role' },
  { label: '员工管理', value: 'staff' },
  { label: '顾客管理', value: 'customer' },
  { label: '菜品管理', value: 'dish' },
  { label: '订单管理', value: 'order' },
  { label: '餐桌管理', value: 'board' },
  { label: '仓库管理', value: 'cargo' },
  { label: '仓储管理', value: 'warehouse' },
  { label: '自检管理', value: 'inspection' },
  { label: '系统管理', value: 'system' },
  { label: '门店管理', value: 'store' },
  { label: '区域管理', value: 'region' },
  { label: '地址管理', value: 'address' },
  { label: '会员管理', value: 'member' },
  { label: '优惠券管理', value: 'coupon' },
  { label: '财务管理', value: 'finance' },
  { label: '薪资管理', value: 'salary' }
]

// 计算属性：分组后的权限列表
const groupedPermissions = computed(() => {
  console.log('计算分组权限，当前权限数据:', permissions.value); // 添加日志
  const groups: Record<string, PermissionGroup> = {}
  
  permissions.value.forEach(permission => {
    const groupName = permission.pcode.split(':')[0]
    if (!groups[groupName]) {
      groups[groupName] = {
        name: getGroupDisplayName(groupName),
        permissions: [],
        checked: false,
        indeterminate: false
      }
    }
    if (searchQuery.value) {
      const searchLower = searchQuery.value.toLowerCase()
      if (
        permission.pname.toLowerCase().includes(searchLower) ||
        permission.pcode.toLowerCase().includes(searchLower) ||
        permission.description.toLowerCase().includes(searchLower)
      ) {
        groups[groupName].permissions.push(permission)
      }
    } else {
      groups[groupName].permissions.push(permission)
    }
  })

  // 更新分组的选中状态
  Object.values(groups).forEach(group => {
    const groupPermissionIds = group.permissions.map(p => p.pid)
    const selectedCount = groupPermissionIds.filter(id => 
      selectedPermissions.value.includes(id)
    ).length

    group.checked = selectedCount === group.permissions.length
    group.indeterminate = selectedCount > 0 && selectedCount < group.permissions.length
  })

  return Object.values(groups)
})

// 获取权限组显示名称
const getGroupDisplayName = (code: string) => {
  const displayNames: Record<string, string> = {
    user: '用户管理',
    role: '角色管理',
    staff: '员工管理',
    customer: '顾客管理',
    dish: '菜品管理',
    order: '订单管理',
    board: '餐桌管理',
    cargo: '仓库管理',
    warehouse: '仓储管理',
    inspection: '自检管理',
    system: '系统管理',
    store: '门店管理',
    region: '区域管理',
    address: '地址管理',
    member: '会员管理',
    coupon: '优惠券管理',
    dish_type: '菜品分类',
    finance: '财务管理',
    salary: '薪资管理'
  }
  return displayNames[code] || code
}

// 判断权限是否禁用
const isPermissionDisabled = (permission: Permission) => {
  // 可以根据实际业务逻辑来设置权限是否可选
  return false
}

// 处理角色选择
const handleRoleSelect = async (index: string) => {
  if (isLoading.value) return;
  
  try {
    isLoading.value = true;
    const roleId = parseInt(index);
    currentRole.value = roles.value.find(role => role.rid === roleId) || null;
    
    if (currentRole.value) {
      // 获取权限列表
      const response = await permissionApi.getPermissions();
      if (response.code === 200) {
        // 确保正确映射数据
        const mappedPermissions = response.data.map((permission: any) => ({
          pid: permission.pid,
          pname: permission.pname,
          pcode: permission.pcode,
          description: permission.description,
          group: permission.pcode.split(':')[0]
        }));
        
        // 直接设置权限数据
        permissions.value = mappedPermissions;
        
        // 等待权限数据设置完成后再设置选中状态
        await new Promise(resolve => setTimeout(resolve, 0));
        await fetchRolePermissions(roleId);
      } else {
        ElMessage.error(response.message || '获取权限列表失败');
      }
    }
  } catch (error) {
    console.error('获取权限列表失败:', error);
    ElMessage.error('获取权限列表失败');
  } finally {
    isLoading.value = false;
  }
}

// 处理权限组选择状态变化
const handleGroupCheckChange = (checked: boolean, group: PermissionGroup) => {
  const groupPermissionIds = group.permissions.map(p => p.pid)
  if (checked) {
    // 添加组内所有未选中的权限
    groupPermissionIds.forEach(id => {
      if (!selectedPermissions.value.includes(id)) {
        selectedPermissions.value.push(id)
      }
    })
  } else {
    // 移除组内所有已选中的权限
    selectedPermissions.value = selectedPermissions.value.filter(
      id => !groupPermissionIds.includes(id)
    )
  }
}

// 全选/取消全选
const handleCheckAll = () => {
  selectedPermissions.value = permissions.value.map(p => p.pid)
}

const handleUncheckAll = () => {
  selectedPermissions.value = []
}

// 处理新增角色
const handleAddRole = () => {
  isEdit.value = false
  roleForm.value = {
    rname: '',
    describes: ''
  }
  roleDialogVisible.value = true
}

// 提交角色表单
const handleSubmitRole = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // TODO: 调用实际的API
        // const response = await fetch('/api/roles', {
        //   method: isEdit.value ? 'PUT' : 'POST',
        //   body: JSON.stringify(roleForm.value)
        // })
        
        ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        roleDialogVisible.value = false
        await fetchRoles()
      } catch (error) {
        console.error('提交角色失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 修改接口调用函数
const addRolePermission = async (rid: number, pid: number) => {
  try {
    const response = await permissionApi.addRolePermission(rid, pid);
    if (response.code !== 200) {
      throw new Error(response.message || '添加权限失败');
    }
  } catch (error) {
    console.error('添加权限失败:', error);
    throw error;
  }
}

const removeRolePermission = async (rid: number, pid: number) => {
  try {
    const response = await permissionApi.removeRolePermission(rid, pid);
    if (response.code !== 200) {
      throw new Error(response.message || '移除权限失败');
    }
  } catch (error) {
    console.error('移除权限失败:', error);
    throw error;
  }
}

// 修改保存权限的函数
const handleSavePermissions = async () => {
  if (!currentRole.value) return;
  
  try {
    saving.value = true;
    const roleId = currentRole.value.rid;
    
    // 获取当前角色原有的权限ID列表
    const originalPermissions = currentRole.value.permissionIds || [];
    
    // 计算需要新增和删除的权限
    const permissionsToAdd = selectedPermissions.value.filter(
      pid => !originalPermissions.includes(pid)
    );
    const permissionsToRemove = originalPermissions.filter(
      pid => !selectedPermissions.value.includes(pid)
    );
    
    // 依次处理每个权限变更
    for (const pid of permissionsToAdd) {
      await addRolePermission(roleId, pid);
    }
    
    for (const pid of permissionsToRemove) {
      await removeRolePermission(roleId, pid);
    }
    
    // 更新本地数据
    currentRole.value.permissionIds = [...selectedPermissions.value];
    currentRole.value.permissionCount = selectedPermissions.value.length;
    
    ElMessage.success('权限配置已更新');
    
    // 重新获取角色权限关联关系
    await fetchRolePermissionsAssociations();
  } catch (error) {
    console.error('保存权限失败:', error);
    ElMessage.error('保存失败，请重试');
  } finally {
    saving.value = false;
  }
}

// API调用函数
const fetchRoles = async () => {
  try {
    const response = await roleApi.getRoles();
    if (response.code === 200) {
      roles.value = response.data.map((role: any) => ({
        rid: role.rid,
        rname: role.rname,
        describes: role.describes,
        permissionCount: 0,
        permissionIds: []
      }));
    } else {
      ElMessage.error(response.message || '获取角色列表失败');
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取角色与权限的关联关系
const fetchRolePermissionsAssociations = async () => {
  try {
    const response = await permissionApi.getRolePermissions();
    if (response.code === 200) {
      const associations = response.data;
      
      // 构建 roleId -> [permissionId] 的映射
      const rolePermissionsMap: Record<number, number[]> = {};
      associations.forEach((item: { rid: number; pid: number }) => {
        if (!rolePermissionsMap[item.rid]) { 
           rolePermissionsMap[item.rid] = [];
        }
        rolePermissionsMap[item.rid].push(item.pid); 
      });

      // 更新 roles 数组中的权限数量和ID列表
      roles.value = roles.value.map(role => {
         const permissionIds = rolePermissionsMap[role.rid] || [];
         return {
           ...role,
           permissionCount: permissionIds.length,
           permissionIds: permissionIds
         };
      });
    } else {
      ElMessage.error(response.message || '获取角色权限关联失败');
    }
  } catch (error) {
    console.error('获取角色权限关联失败:', error);
    ElMessage.error('获取角色权限关联失败');
  }
}

const fetchRolePermissions = async (roleId: number) => {
  try {
    // 从已加载的 roles 数据中找到当前角色的权限ID列表
    const role = roles.value.find(r => r.rid === roleId);
    if (role && role.permissionIds) {
      // 确保权限数据已经加载完成
      if (permissions.value.length > 0) {
        selectedPermissions.value = [...role.permissionIds];
      }
    } else {
      selectedPermissions.value = [];
    }
  } catch (error) {
    console.error('获取角色权限失败:', error);
    ElMessage.error('获取角色权限失败');
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    isLoading.value = true;
    // 先获取角色列表
    await fetchRoles();
    // 再获取权限关联
    await fetchRolePermissionsAssociations();

    // 如果有角色，选择第一个角色并加载其权限
    if (roles.value.length > 0) {
      await handleRoleSelect(String(roles.value[0].rid));
    }
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('初始化失败');
  } finally {
    isLoading.value = false;
  }
})

// 新增权限的处理函数
const handleAddPermission = () => {
  permissionForm.value = {
    group: '',
    pname: '',
    pcode: '',
    description: ''
  }
  permissionDialogVisible.value = true
}

// 监听权限大类变化，自动生成权限编码前缀
watch(() => permissionForm.value.group, (newVal) => {
  if (newVal && !permissionForm.value.pcode.startsWith(newVal + ':')) {
    permissionForm.value.pcode = newVal + ':'
  }
})

// 提交权限表单
const handleSubmitPermission = async () => {
  if (!permissionFormRef.value) return
  
  await permissionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // TODO: 调用实际的API
        // const response = await fetch('/api/permissions', {
        //   method: 'POST',
        //   body: JSON.stringify(permissionForm.value)
        // })
        
        ElMessage.success('新增权限成功')
        permissionDialogVisible.value = false
        // 重新加载当前角色的权限
        if (currentRole.value) {
          await handleRoleSelect(String(currentRole.value.rid))
        }
      } catch (error) {
        console.error('新增权限失败:', error)
        ElMessage.error('新增权限失败')
      }
    }
  })
}
</script>

<style scoped>
.permission-management {
  margin-left: 200px;
  margin-top: 45px;
  padding: 20px;
  height: 94vh;
  box-sizing: border-box;
  background-color: #f0f2f5;
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100% - 40px); /* 减去padding的高度 */
}

/* 左侧角色列表样式 */
.role-section {
  width: 280px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.section-header {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.role-menu {
  border-right: none;
}

.role-menu :deep(.el-menu-item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-tag {
  margin-left: 8px;
}

/* 右侧权限配置样式 */
.permission-section {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  height: calc(100vh - 120px); /* 减去上下padding的高度 */
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-top: 16px;
}

.permission-search {
  width: 220px;
}

.permission-groups {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  max-height: calc(100vh - 220px); /* 调整最大高度，为头部和底部留出空间 */
  overflow-y: auto;
  padding-right: 6px;
}

.permission-group {
  margin-bottom: 16px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.group-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.permission-list {
  margin-top: 12px;
}

.permission-item {
  display: flex;
  flex-direction: column;
}

.permission-name {
  font-size: 14px;
}

.permission-code {
  font-size: 12px;
  color: #666;
}

/* 自定义滚动条样式 */
.permission-groups::-webkit-scrollbar {
  width: 6px;
}

.permission-groups::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.permission-groups::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.permission-groups::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.no-role-selected {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .role-section {
    width: 100%;
  }

  .permission-groups {
    grid-template-columns: 1fr;
  }
}

/* 添加新样式 */
.w-full {
  width: 100%;
}
</style> 